from rest_framework import serializers
from baykeadmin.config import default


class CaptchaSerializer(serializers.Serializer):
    """ 验证码序列化器 """
    captcha = serializers.CharField(
        label="验证码", 
        max_length=default.FONT_CAPTCHA_LENGTH, 
        min_length=default.FONT_CAPTCHA_LENGTH,
        write_only=True
    )
    uid = serializers.CharField(
        label="验证码id", 
        max_length=100, 
        min_length=10, 
        write_only=True
    )

    def validate(self, attrs):
        from django.core.cache import cache

        if not cache.get(attrs['uid']):
            raise serializers.ValidationError("验证码已过期")
        if cache.get(attrs['uid']).lower() != attrs['captcha'].lower():  # 验证码验证
            raise serializers.ValidationError("验证码错误")
        cache.delete(attrs['uid'])
        return super().validate(attrs)
    

class SendEmailCodeSerializer(serializers.Serializer):
    """ 发送邮箱验证码序列化器 
    """
    email = serializers.EmailField(label="邮箱", required=True)


class VerifyEmailCodeSerializer(serializers.Serializer):
    """ 验证邮箱验证码序列化器 
    """
    email = serializers.EmailField(label="邮箱", required=True)
    code = serializers.CharField(
        label="验证码", 
        required=True, 
        max_length=default.EMAIL_CAPTCHA_LENGTH, 
        min_length=default.EMAIL_CAPTCHA_LENGTH,
        write_only=True
    )

    def validate(self, attrs):
        attrs = super().validate(attrs)
        from django.core.cache import cache
        item_code = cache.get(attrs['email'])
        if item_code != attrs['code']:
            raise serializers.ValidationError("验证码已过期或输入有误")
        return attrs